'use strict';

angular.module('Common').controller('ParameterController',
    ['$scope', '$compile', '$stateParams', 'BaseModule', 'BaseFunction', 'ExtendEnumService', 'BaseEnum', 'BaseConst', '$location', 'Authentication',
    function($scope, $compile, $stateParams, BaseModule, BaseFunction, ExtendEnumService, BaseEnum, BaseConst, $location, Authentication) {
    	$scope.btnSave = function(){
    		for(var i=0; i<$scope.Module.Parameter.Records.length; i++){
    			if(!$scope.Module.Parameter.Records[i].IsEmpty || !$scope.Module.Parameter.Records[i].IsEmpty){
	    			if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.TextBox.Value){
	    				if($scope.Module.Parameter.Records[i].Value == ''){
	    					BaseFunction.alert($scope.Module.Parameter.Records[i].Name + "：值不能为空！", "保存错误");
	    					return;
	    				}
	    			}
	    			else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.NumberBox.Value){
	    				if($scope.Module.Parameter.Records[i].Value == null){
	    					BaseFunction.alert($scope.Module.Parameter.Records[i].Name + "：值不能为空！", "保存错误");
	    					return;
	    				}
	    			}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.PercentBox.Value){
	        			if($scope.Module.Parameter.Records[i].Value == null){
	    					BaseFunction.alert($scope.Module.Parameter.Records[i].Name + "：值不能为空！", "保存错误");
	    					return;
	    				}
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.Refer.Value){
	        			if($scope.Module.Parameter.Records[i].RefValue[$scope.Module.Parameter.Records[i].CodeField] == ''){
	    					BaseFunction.alert($scope.Module.Parameter.Records[i].Name + "：值不能为空！", "保存错误");
	    					return;
	    				}
	    				else{
	    					$scope.Module.Parameter.Records[i]['Key'] = $scope.Module.Parameter.Records[i].RefValue[$scope.Module.Parameter.Records[i].KeyField];
	    					$scope.Module.Parameter.Records[i]['Value'] = $scope.Module.Parameter.Records[i].RefValue[$scope.Module.Parameter.Records[i].CodeField];
	    					$scope.Module.Parameter.Records[i]['Text'] = $scope.Module.Parameter.Records[i].RefValue[$scope.Module.Parameter.Records[i].TextField];
	    				}
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.Calendar.Value){
	        			if($scope.Module.Parameter.Records[i].Value == BaseConst.DateTime.Min){
	    					BaseFunction.alert($scope.Module.Parameter.Records[i].Name + "：值不能为空！", "保存错误");
	    					return;
	    				}
	        		}
	        	}
    		}

            $scope.Module.Parameter.save(function(){
            	$scope.loadData();
            });
        };

        $scope.btnCancel = function(){
            $scope.loadData();
        };

    	$scope.rowClick = function(recordId){
    		if($scope.Module.Parameter.FocusedRecord == null){
    			$scope.Module.Parameter.FocusedRecord = $scope.Module.Parameter.findRecordById(recordId);
	    		document.getElementById(recordId).style.backgroundColor = '#FAEBB2';
    		}
    		else if(recordId != $scope.Module.Parameter.FocusedRecord._id){
    			document.getElementById($scope.Module.Parameter.FocusedRecord._id).removeAttribute('style');
    			$scope.Module.Parameter.FocusedRecord = $scope.Module.Parameter.findRecordById(recordId);
	    		document.getElementById(recordId).style.backgroundColor = '#FAEBB2';
    		}
    	};

    	//初始化
        BaseModule.initModule($scope, 'Parameter');
        $scope.Module.Parameter.PageSize = 1000;
        $scope.Module.Parameter.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;
        $scope.Module.Parameter.OrderBy = {Code: 1};
        $scope.Module.Parameter.Condition = {IsDisplay: true};

        $scope.Enum = {};

        $scope.loadData = function(){
        	$scope.Enum = {};
        	var contentTD = document.getElementById('TDContent');
        	contentTD.innerHTML = "";

        	$scope.Module.Parameter.load(null, null, function(records){
	        	var callBacks = {};
	        	
	        	var tdInnerHtml = '<table id="tableContent" class="ParameterContent" cellpadding="0" cellspacing="0" style="width:100%;">' + 
					'<colgroup>' + 
						'<col width="150px"/>' + 
						'<col width="150px"/>' + 
						'<col width="200px"/>' + 
					'</colgroup>';
	        	for(var i=0; i<$scope.Module.Parameter.Records.length; i++){
	        		tdInnerHtml += '<tr id="' + $scope.Module.Parameter.Records[i]._id + '">' + 
							'<td title="' + $scope.Module.Parameter.Records[i].Code + '">' + $scope.Module.Parameter.Records[i].Code + '</td>' + 
							'<td title="' + $scope.Module.Parameter.Records[i].Name + '">' + $scope.Module.Parameter.Records[i].Name + '</td>';

	        		if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.TextBox.Value){
	        			
							tdInnerHtml += '<td style="padding:0px;"><TextBox style="border-radius: 0px;" value="Module.Parameter.Records[' + i.toString() + '].Value"></TextBox></td>';
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.CheckBox.Value){
	        			if($scope.Module.Parameter.Records[i].Value == 'true'){
	        				$scope.Module.Parameter.Records[i].Value = true;
	        			}
	        			else{
	        				$scope.Module.Parameter.Records[i].Value = false;
	        			}

	        			tdInnerHtml += '<td style="text-align: center;"><CheckBox value="Module.Parameter.Records[' + i.toString() + '].Value"></TextBox></td>';

	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.NumberBox.Value){
	        			$scope.Module.Parameter.Records[i].Value = parseFloat($scope.Module.Parameter.Records[i].Value);
						tdInnerHtml += '<td style="padding:0px;"><NumberBox style="border-radius: 0px;" value="Module.Parameter.Records[' + i.toString() + '].Value"></NumberBox></td>';
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.PercentBox.Value){
	        			$scope.Module.Parameter.Records[i].Value = parseFloat($scope.Module.Parameter.Records[i].Value);
						tdInnerHtml += '<td style="padding:0px;"><PercentBox style="border-radius: 0px;" value="Module.Parameter.Records[' + i.toString() + '].Value"></PercentBox></td>';
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.DropDownList.Value){
	        			$scope.Module.Parameter.Records[i].Value = parseInt($scope.Module.Parameter.Records[i].Value);
	        			var code = $scope.Module.Parameter.Records[i].Code;
	        			var enumCode = $scope.Module.Parameter.Records[i].EnumCode;
	        			callBacks[code] = false;
	        			if(enumCode.indexOf('.') > -1){
		        			$scope.Enum[enumCode] = BaseFunction.getEnum(enumCode);
		        			callBacks[code] = true;
	        				generateHtml();
		        		}
		        		else{
		        			ExtendEnumService.getExtendEnum(enumCode, function(enum1){
		        				$scope.Enum[enumCode] = enum1;
		        				callBacks[code] = true;
		        				generateHtml();
		        			});
		        		}
	        			tdInnerHtml += '<td style="padding:0px;overflow:visible;"><DropDownList style="border-radius: 0px;" Enum="Enum[\'' + $scope.Module.Parameter.Records[i].EnumCode + '\']" value="Module.Parameter.Records[' + i.toString() + '].Value"></DropDownList></td>';
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.Refer.Value){
	        			$scope.Module.Parameter.Records[i]["RefValue"] = {};
	        			$scope.Module.Parameter.Records[i]["RefValue"][$scope.Module.Parameter.Records[i].KeyField] = $scope.Module.Parameter.Records[i].Key;
	        			$scope.Module.Parameter.Records[i]["RefValue"][$scope.Module.Parameter.Records[i].CodeField] =  $scope.Module.Parameter.Records[i].Value;
	        			$scope.Module.Parameter.Records[i]["RefValue"][$scope.Module.Parameter.Records[i].TextField] = $scope.Module.Parameter.Records[i].Text;
	        			tdInnerHtml += '<td style="padding:0px;overflow:visible;"><Refer IsGrid="true" style="margin-bottom:0px;" Condition="' + $scope.Module.Parameter.Records[i].Condition + '" ' + 
	                        'OrderBy="' + $scope.Module.Parameter.Records[i].OrderBy + '" ' + 
	                        'Populate="' + $scope.Module.Parameter.Records[i].Populate + '" ' +
	                        'value="Module.Parameter.Records[' + i.toString() + '].RefValue" ' + 
	                        'keyfield="' + $scope.Module.Parameter.Records[i].KeyField + '" codefield="' + $scope.Module.Parameter.Records[i].CodeField + '" textfield="' + $scope.Module.Parameter.Records[i].TextField + '" ' + 
	                        'EntityName="' + $scope.Module.Parameter.Records[i].EntityName + '" windowtitle="' + $scope.Module.Parameter.Records[i].WindowTitle + '">';

	                    var displayColumns = eval($scope.Module.Parameter.Records[i].DisplayColumns);
	                    for(var j=0; j<displayColumns.length; j++){
	                        tdInnerHtml += '<RColumn'
	                        if (displayColumns[j].Type != undefined && displayColumns[j].Type != "") {
	                            tdInnerHtml += ' type="' + displayColumns[j].Type + '"';
	                        }
	                        if (displayColumns[j].DisplayName != undefined && displayColumns[j].DisplayName != "") {
	                            tdInnerHtml += ' displayname="' + displayColumns[j].DisplayName + '"';
	                        }
	                        if (displayColumns[j].Width != undefined && displayColumns[j].Width != "") {
	                            tdInnerHtml += ' width="' + displayColumns[j].Width + '"';
	                        }
	                        if (displayColumns[j].ValueField != undefined && displayColumns[j].ValueField != "") {
	                            tdInnerHtml += ' valuefield="' + displayColumns[j].ValueField + '"';
	                        }
	                        if (displayColumns[j].Enum != undefined && displayColumns[j].Enum != "") {
	                            tdInnerHtml += ' enum="' + displayColumns[j].Enum + '"';
	                        }
	                        if (displayColumns[j].Round != undefined && displayColumns[j].Round != "") {
	                            tdInnerHtml += ' round="' + displayColumns[j].Round + '"';
	                        }
	                        if (displayColumns[j].CalendarType != undefined && displayColumns[j].CalendarType != "") {
	                            tdInnerHtml += ' calendartype="' + displayColumns[j].CalendarType + '"';
	                        }
	                        tdInnerHtml += '></RColumn>';
	                    }
	                    tdInnerHtml += '</Refer></td>';
	        		}
	        		else if($scope.Module.Parameter.Records[i].Type == BaseEnum.ControlType.Calendar.Value){
	        			if($scope.Module.Parameter.Records[i].CalendarType == BaseEnum.DateTimeFormat.Date.Value){
							tdInnerHtml += '<td style="padding:0px;overflow:visible;"><Calendar type="Date" IsGrid="true" value="Module.Parameter.Records[' + i.toString() + '].Value"></Calendar></td>';
		        		}
		        		else{
		        			tdInnerHtml += '<td style="padding:0px;overflow:visible;"><Calendar type="DateTime" IsGrid="true" value="Module.Parameter.Records[' + i.toString() + '].Value"></Calendar></td>';
		        		}
	        		}

	        		tdInnerHtml += '<td title="' + $scope.Module.Parameter.Records[i].Remark + '">' + $scope.Module.Parameter.Records[i].Remark + '</td>' + 
						'</tr>';
	        	}
	        	tdInnerHtml += '</table>';

	        	var isGenerateComplete = true;
	        	generateHtml();

	        	function generateHtml(){
	        		if(isGenerateComplete){
	        			var isCallbackComplet = true;
	        			for(var p in callBacks){
	        				if(callBacks[p] == false){
	        					isCallbackComplet = false;
	        					break;
	        				}
	        			}
	        			if(isCallbackComplet){
	        				$compile(tdInnerHtml)($scope, function (clone, $scope) {
				                contentTD.appendChild(clone[0]);
				                var rows = document.getElementById('tableContent').rows;
				                for(var i=0; i<rows.length; i++){
				                	rows[i].addEventListener('click', function(){ 
				                		var domRow = event.srcElement;
						                while (domRow.tagName.toLowerCase() != "tr" || !domRow.getAttribute('id')) {
						                    domRow = domRow.parentNode;
						                }
						                $scope.$apply( $scope.rowClick(domRow.getAttribute('id'))); }, true);
				                }
				                if($scope.Module.Parameter.FocusedRecord != null){
					                document.getElementById('tableContent').rows[0].style.backgroundColor = '#FAEBB2';
					            }
				            });
	        			}
	        		}	        	
		        }
	        });
        };

        $scope.loadData();
    }
]);